package com.saltedfish.tool.ui

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import cn.droidlover.xdroidmvp.BaseApplication
import cn.droidlover.xdroidmvp.base.FragmentBasePagerAdapter
import cn.droidlover.xdroidmvp.base.SimpleListener
import cn.droidlover.xdroidmvp.event.BusProvider
import cn.droidlover.xdroidmvp.log.XLog
import cn.droidlover.xdroidmvp.util.ActivityManager
import cn.droidlover.xdroidmvp.util.AppUtil
import com.blankj.rxbus.RxBus
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.saltedfish.tool.R
import com.saltedfish.tool.dao.AppDataUtils
import com.saltedfish.tool.dao.DayDBDao
import com.saltedfish.tool.dao.SubFlagModelDao
import com.saltedfish.tool.dialog.UIUpdateVersionDialog
import com.saltedfish.tool.model.*
import com.saltedfish.tool.present.MainAP
import com.saltedfish.tool.ui.achievement.FragmentAchievement
import com.saltedfish.tool.ui.calendar.FragmentCalendar
import com.saltedfish.tool.ui.flag.FragmentFlag
import com.saltedfish.tool.util.CalendarReminderUtils
import com.saltedfish.tool.util.DateUtils
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main.mViewPager
import java.text.SimpleDateFormat
import java.util.*


class MainActivity : XActivity<MainAP>() {

    var adapter: FragmentBasePagerAdapter? = null

    override fun newP(): MainAP? {
        return MainAP()
    }

    override fun getLayoutId(): Int {
       // setShouldPaddingTop(false)
        setStatusColor(true, 1)
        setStatusBlack()
//        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
        /*window.addFlags(
            WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED //锁屏状态下显示
                    or WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD //解锁
                    or WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON //保持屏幕长亮
                    or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
        ) //打开屏幕*/

        return R.layout.activity_main
    }

    var dayDBDao: DayDBDao? = null
    var subFlagModelDao: SubFlagModelDao? = null
//    private val formatterDay = SimpleDateFormat("yyyy-MM-dd")

    var cal: Calendar? = null

    override fun initData(savedInstanceState: Bundle?) {
        var database = AppDataUtils.initRoom(context)
        dayDBDao = database.dayDBDao()
        subFlagModelDao = database.subFlagDao()

        adapter = FragmentBasePagerAdapter(
                supportFragmentManager,
                FragmentFlag.newInstance(), FragmentCalendar.newInstance(),
                FragmentAchievement.newInstance()
        )

        val mTitles = arrayOf("Flag", "日程", "成就")
        val mIconUnSelectIds = intArrayOf(
                R.drawable.tab_button_flag_default, R.drawable.tab_button_calendar_default,
                R.drawable.tab_button_achievement_default
        )
        val mIconSelectIds = intArrayOf(
                R.drawable.tab_button_flag_selected, R.drawable.tab_button_calendar_selected,
                R.drawable.tab_button_achievement_selected
        )
        val mTabEntities =
            ArrayList<CustomTabEntity>()
        for (i in mTitles.indices) {
            mTabEntities.add(
                    TabEntityBean(
                            mTitles[i],
                            mIconSelectIds[i],
                            mIconUnSelectIds[i]
                    )
            )
        }

        mViewPager.adapter = adapter

        if(mViewPager !=null){
            mViewPager.offscreenPageLimit = 3
        }
        mTabLayout.setTabData(mTabEntities)

       cal = Calendar.getInstance()

        var flagModelList =  subFlagModelDao!!.getAllSmallTableByStatus("进行中")
//        XLog.e("----flagModelList-----"+flagModelList.size)
        if(flagModelList.size !=0){
            mViewPager.currentItem = 1
            mTabLayout.currentTab = 1
        }

            mTabLayout.setOnTabSelectListener(object : OnTabSelectListener {
                override fun onTabSelect(position: Int) {
                    mViewPager.currentItem = position
//                    XLog.e("-position---${position}")
                    if(position ==1){
                        val modelInfo = ModelInfo()
                        modelInfo.updateCalendar2 = true
                        BusProvider.getBus().post(modelInfo)
                    }
                }

                override fun onTabReselect(position: Int) {
                }
            })

        BusProvider.getBus().subscribe(context,
                RxBus.Callback<ModelInfo> { modelInfo ->
                    if(modelInfo !=null && modelInfo.updateTab){
                        mViewPager.currentItem = 0
                        mTabLayout.currentTab = 0
                    }

                })

        p.getLatestVersion()

        Thread{

            var subFlagLists = subFlagModelDao!!.getAllByStatusForProgress("已延期", 1.0f,0)
           // XLog.e("---延期的数据--------"+subFlagLists.toString())
            if(subFlagLists.size !=0){
                for (item in subFlagLists) {
                    insertDayDBTable(item)
                }
            }
        }.start()


    }

    private val formatterDay = SimpleDateFormat("yyyy-MM-dd")


    /**
     * 添加日程
     */
    private fun insertDayDBTable(subFlagModel: SmallTable) {
        if (dayDBDao != null) {
            val weeks: Array<String> = subFlagModel.repeatDay.split(" ").toTypedArray()
            val list: MutableList<String> = ArrayList()
            val today = cal!!.time
            var delayCount = subFlagModel.tick - subFlagModel.tickNum
            var dou = delayCount / weeks.size
            var num = Math.ceil(dou.toDouble())
            cal!!.add(Calendar.DATE, (7 * num).toInt())
            val selectDayDate = cal!!.time
            for (week in weeks) {
                list.addAll(DateUtils.getWeekly(formatterDay.format(today), formatterDay.format(selectDayDate), week))
            }
            for (time in list) {
                val dayTable = DayTable()
                dayTable.day = time
                dayTable.title = subFlagModel.title
                dayTable.fId = subFlagModel.fId
                dayTable.isTick = false
                dayTable.repeatTime = subFlagModel.repeatTime
                dayTable.subId = subFlagModel.subId
                dayTable.createTime = subFlagModel.createTime
                dayDBDao!!.insert(dayTable)
            }
            subFlagModel.delayCount = 1
            subFlagModelDao!!.update(subFlagModel)
        }
    }


    override fun onActivityResult(
            requestCode: Int, resultCode: Int, data: Intent?
    ) {
        super.onActivityResult(requestCode, resultCode, data)
//        if (supportFragmentManager.fragments != null && supportFragmentManager.fragments.isNotEmpty()) {
//            val fragments: List<Fragment> = supportFragmentManager.fragments
//            for (i in fragments.indices) {
//                if (i == 2) {
//                    fragments[i].onActivityResult(requestCode, resultCode, data)
//                }
//            }
//        }
    }


    private var exitTime: Long = 0

    override fun onBackPressed() {
        if (System.currentTimeMillis() - exitTime > 2500) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show()
            exitTime = System.currentTimeMillis()
        } else {
            //安全退出
            //stopService(intentIm)
            ActivityManager.getInstance().exitApp()
        }
    }


    override fun onDestroy() {
//        stopService(intentIm)
        super.onDestroy()
    }


    fun getLatestVersionSuccess(updateVersion: UpdateVersion) {
         var version =  AppUtil.getVersionName(BaseApplication.getInstance())
            if(updateVersion !=null){
                XLog.e(version+"----------"+updateVersion.versionName)
                if(version < updateVersion.versionName){
                    if (updateDialog == null) {
                        updateDialog = UIUpdateVersionDialog(context)
                        updateDialog!!.setSimpleListener(object : SimpleListener<Int>() {
                            override fun onClick(type: String) {
//                    if (type == "save") {
//                        initDataShow()
//                        createFlagDialog!!.dismiss()
//                    }
                            }
                        })
                    }
                    updateDialog!!.updateVersion(updateVersion)
                    updateDialog!!.show()
                }

            }
    }


    private var  updateDialog : UIUpdateVersionDialog? =null




}
